// app/service/reconciliation_result_service.js
'use strict';

const Service = require('egg').Service;

class ReconciliationResultService extends Service {
  // 获取对账结果列表
  async getResultList(page, pageSize, params) {
    const { ctx } = this;
    const { matchStatus, minConfidence, maxConfidence } = params;
    
    const query = {
      where: {},
      include: [
        {
          model: ctx.model.SalesOrderModel,
          as: 'salesOrder',
          attributes: ['id', 'platformOrderId', 'orderAmount', 'orderDate']
        },
        {
          model: ctx.model.BankTransactionModel,
          as: 'bankTransaction',
          attributes: ['id', 'transactionId', 'payerName', 'amount', 'transactionDate']
        }
      ]
    };
    
    if (matchStatus) {
      query.where.matchStatus = matchStatus;
    }
    
    if (minConfidence || maxConfidence) {
      query.where.matchConfidence = {};
      
      if (minConfidence) {
        query.where.matchConfidence[ctx.app.Sequelize.Op.gte] = parseFloat(minConfidence);
      }
      
      if (maxConfidence) {
        query.where.matchConfidence[ctx.app.Sequelize.Op.lte] = parseFloat(maxConfidence);
      }
    }
    
    const result = await ctx.model.ReconciliationResultModel.findAndCountAll({
      ...query,
      limit: parseInt(pageSize),
      offset: (parseInt(page) - 1) * parseInt(pageSize),
      order: [['matched_at', 'DESC']]
    });
    
    return {
      list: result.rows,
      total: result.count
    };
  }
  
  // 根据ID获取对账结果
  async getResultById(id) {
    const { ctx } = this;
    return await ctx.model.ReconciliationResultModel.findByPk(id, {
      include: [
        {
          model: ctx.model.SalesOrderModel,
          as: 'salesOrder'
        },
        {
          model: ctx.model.BankTransaction,
          as: 'bankTransaction'
        }
      ]
    });
  }
  
  // 创建对账结果
  async createResult(resultData) {
    const { ctx } = this;
    return await ctx.model.ReconciliationResultModel.create(resultData);
  }
  
  // 更新对账结果
  async updateResult(id, resultData) {
    const { ctx } = this;
    const result = await ctx.model.ReconciliationResultModel.findByPk(id);
    
    if (!result) {
      throw new Error('对账结果不存在');
    }
    
    return await result.update(resultData);
  }
  
  // 删除对账结果
  async deleteResult(id) {
    const { ctx } = this;
    const result = await ctx.model.ReconciliationResultModel.findByPk(id);
    
    if (!result) {
      throw new Error('对账结果不存在');
    }
    
    return await result.destroy();
  }
  
  // 确认对账结果
  async confirmResult(id, confirmedBy) {
    const { ctx } = this;
    const result = await ctx.model.ReconciliationResultModel.findByPk(id);
    
    if (!result) {
      throw new Error('对账结果不存在');
    }
    
    return await result.update({
      matchStatus: 'confirmed',
      confirmedBy: confirmedBy,
      confirmedAt: new Date()
    });
  }
  
  // 拒绝对账结果
  async rejectResult(id, notes) {
    const { ctx } = this;
    const result = await ctx.model.ReconciliationResultModel.findByPk(id);
    
    if (!result) {
      throw new Error('对账结果不存在');
    }
    
    return await result.update({
      matchStatus: 'rejected',
      notes: notes
    });
  }
}

module.exports = ReconciliationResultService;